using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Xml;
using System.IO;


public partial class upload : BasePage
{
        String mChiDesc = HttpContext.GetGlobalResourceObject("Resource", "DescChi").ToString();
        String mChiCode = HttpContext.GetGlobalResourceObject("Resource", "CodeChi").ToString();
        String mChiSize = HttpContext.GetGlobalResourceObject("Resource", "SizeChi").ToString();
        String mEngDesc = "Product Description";
        String mEngCode = "Product Code";
        String mEngSize = "Size (W x L)";

        String cat1 = "Inflatable items";
        String cat2 = "OEM Products";
        String cat3 = "Party Flavors";
        String cat4 = "Seasonal Toys";

        String image_path = "static/picasa/";
        String root_node = "album/images";
        String child_node = "album/images/image";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!(Page.IsPostBack))
            {
                DDL_File1Cat.Items.Clear();
                DDL_File1Cat.Items.Add(cat1);
                DDL_File1Cat.Items.Add(cat2);
                DDL_File1Cat.Items.Add(cat3);
                DDL_File1Cat.Items.Add(cat4);

                DDL_viewcat.Items.Clear();
                DDL_viewcat.Items.Add("Please Select a category");
                DDL_viewcat.Items.Add(cat1);
                DDL_viewcat.Items.Add(cat2);
                DDL_viewcat.Items.Add(cat3);
                DDL_viewcat.Items.Add(cat4);

                ChiDesc.Text = mChiDesc + " : ";
                ChiCode.Text = mChiCode + " : ";
                ChiSize.Text = mChiSize + " : ";
                EngDesc.Text = mEngDesc + " : ";
                EngCode.Text = mEngCode + " : ";
                EngSize.Text = mEngSize + " : ";


            }
            else
            {
            }
        }

        protected void Btn_Upload_Click(object sender, EventArgs e)
        {
            try
            {
                if ((FileUpload1.HasFile) &&
                    ((FileUpload1.FileName.ToLower().EndsWith(".bmp")) || (FileUpload1.FileName.ToLower().EndsWith(".jpg")) ||
                     (FileUpload1.FileName.ToLower().EndsWith(".jpeg")) || (FileUpload1.FileName.ToLower().EndsWith(".gif")) ||
                     (FileUpload1.FileName.ToLower().EndsWith(".tif")) || (FileUpload1.FileName.ToLower().EndsWith(".tiff")) ||
                     (FileUpload1.FileName.ToLower().EndsWith(".png"))))
                {

                    /* save image and save to original size */
                    FileUpload1.SaveAs(Server.MapPath(image_path) + DDL_File1Cat.SelectedValue + "/images/" + FileUpload1.FileName);

                    /* start - resizing image and save to thumbnails */
                    string FileToResize = Server.MapPath(image_path) + DDL_File1Cat.SelectedValue + "/images/" + FileUpload1.FileName;
                    Bitmap originalBitmap = Bitmap.FromFile(FileToResize, true) as Bitmap;
                    int new_height = 0;
                    int new_width = 0;
                    if (originalBitmap.Width > originalBitmap.Height)
                    {
                        new_width = 220;
                        new_height = (int)(originalBitmap.Height * 220 / originalBitmap.Width );
                    }
                    else
                    {
                        new_height = 220;
                        new_width = (int)(originalBitmap.Width * 220 / originalBitmap.Height);
                    }
                    Bitmap newbmp = new Bitmap(new_width, new_height);
                    using (originalBitmap)
                    {
                        using (newbmp)
                        {
                            double WidthVsHeightRatio = (float)originalBitmap.Width / (float)originalBitmap.Height;

                            using (Graphics newg = Graphics.FromImage(newbmp))
                            {
                                newg.Clear(Color.White);
                                newg.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                newg.DrawImage(originalBitmap, 0, 0, new_width, new_height);
                                newg.Save();
                            }

                            newbmp.Save(Server.MapPath(image_path) + DDL_File1Cat.SelectedValue + "/thumbnails/" + FileUpload1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                            lbl_msg.Text = "Uplaod success";
                        }
                    }
                    /* end - resizing image and save to thumbnails */


                    /* start - modifying eng xml doc */
                    string filename = Server.MapPath(image_path) + DDL_File1Cat.SelectedValue + "/index.xml";
                    String eng_desc_xml = "&lt;table class=\"gallery\"&gt;&lt;colgroup&gt;&lt;col class=\"col1\" /&gt;&lt;col class=\"col2\" /&gt;&lt;/colgroup&gt;&lt;tr&gt;&lt;td&gt;" + mEngDesc + "&lt;/td&gt;&lt;td&gt;" + txt_EngDesc.Text + "&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;" + mEngCode + "&lt;/td&gt;&lt;td&gt;" + txt_EngCode.Text + "&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;" + mEngSize + "&lt;/td&gt;&lt;td&gt;" + txt_EngSize.Text + "&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;";
                    XmlDocument doc = new XmlDocument();
                    doc.Load(filename);
                    string childXml = "<image><itemLargeImage>images/" + FileUpload1.FileName + "</itemLargeImage><itemThumbnailImage>thumbnails/" + FileUpload1.FileName + "</itemThumbnailImage><itemCaption>" + eng_desc_xml + "</itemCaption><itemDescp>" + txt_EngDesc.Text + "</itemDescp></image>";
                    XmlDocument childDoc = new XmlDocument();
                    childDoc.LoadXml(childXml);
                    XmlNode parentNode = doc.SelectSingleNode(root_node);
                    XmlNode childNode = childDoc.SelectSingleNode("image");
                    XmlNode transformedChild = doc.ImportNode(childNode, true);
                    parentNode.AppendChild(transformedChild);
                    doc.Save(filename);
                    /* end - modifying eng xml doc */

                    /* start - modifying chi xml doc */
                    filename = Server.MapPath(image_path) + DDL_File1Cat.SelectedValue + "/index_chi.xml";
                    String chi_desc_xml = "&lt;table class=\"gallery\"&gt;&lt;colgroup&gt;&lt;col class=\"col1\" /&gt;&lt;col class=\"col2\" /&gt;&lt;/colgroup&gt;&lt;tr&gt;&lt;td&gt;" + mChiDesc + "&lt;/td&gt;&lt;td&gt;" + txt_ChiDesc.Text + "&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;" + mChiCode + "&lt;/td&gt;&lt;td&gt;" + txt_ChiCode.Text + "&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;" + mChiSize + "&lt;/td&gt;&lt;td&gt;" + txt_ChiSize.Text + "&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;";
                    doc = new XmlDocument();
                    doc.Load(filename);
                    childXml = "<image><itemLargeImage>images/" + FileUpload1.FileName + "</itemLargeImage><itemThumbnailImage>thumbnails/" + FileUpload1.FileName + "</itemThumbnailImage><itemCaption>" + chi_desc_xml + "</itemCaption><itemDescp>" + txt_ChiDesc.Text + "</itemDescp></image>";
                    childDoc = new XmlDocument();
                    childDoc.LoadXml(childXml);
                    parentNode = doc.SelectSingleNode(root_node);
                    childNode = childDoc.SelectSingleNode("image");
                    transformedChild = doc.ImportNode(childNode, true);
                    parentNode.AppendChild(transformedChild);
                    doc.Save(filename);
                    /* end - modifying chi xml doc */

                    binddata();
                }
                else
                {
                    lbl_msg.Text = "Document's type mismatch. Please upload image file.";
                }
            }
            catch (Exception ex)
            {
                // Handle your exception here
                lbl_msg.Text = "Fail to uplaod";
            }

        }

        protected void DDL_viewcat_SelectedIndexChanged(object sender, EventArgs e)
        {
            binddata();
        }

        private void binddata()
        {
            if (DDL_viewcat.SelectedValue == "Please Select a category")
            {
                GVCat.DataSource = null;
                GVCat.DataBind();
            }
            else
            {
                string filename = Server.MapPath(image_path) + DDL_viewcat.SelectedValue + "/index.xml";
                XmlDocument doc = new XmlDocument();
                doc.Load(filename);
                XmlNodeList itemsNode = doc.SelectNodes(child_node);

                string filename2 = Server.MapPath(image_path) + DDL_viewcat.SelectedValue + "/index_chi.xml";
                XmlDocument doc2 = new XmlDocument();
                doc2.Load(filename2);
                XmlNodeList itemsNode2 = doc2.SelectNodes(child_node);

                DataTable dt = new DataTable();
                dt.Columns.Add("LargeImage", Type.GetType("System.String"));
                dt.Columns.Add("ThumbnailImage", Type.GetType("System.String"));
                dt.Columns.Add("ImageURL", Type.GetType("System.String"));
                dt.Columns.Add("Eng_desc", Type.GetType("System.String"));
                dt.Columns.Add("Eng_code", Type.GetType("System.String"));
                dt.Columns.Add("Eng_size", Type.GetType("System.String"));
                dt.Columns.Add("Chi_desc", Type.GetType("System.String"));
                dt.Columns.Add("Chi_code", Type.GetType("System.String"));
                dt.Columns.Add("Chi_size", Type.GetType("System.String"));

                for (int i = 0; i < itemsNode.Count; i++)
                {
                    XmlNode xn = itemsNode.Item(i);
                    XmlNode xc = itemsNode2.Item(i);
                    String Large = xn["itemLargeImage"].InnerText;
                    String small = xn["itemThumbnailImage"].InnerText;
                    String Eng_desc = xn["itemCaption"].InnerText;
                    String Chi_desc = xc["itemCaption"].InnerText;
                    if (Eng_desc.Contains(mEngDesc) && Eng_desc.Contains(mEngCode) && Eng_desc.Contains(mEngSize) &&
                        Chi_desc.Contains(mChiDesc) && Chi_desc.Contains(mChiCode) && Chi_desc.Contains(mChiSize))
                    {
                        String P_desc_e;
                        String P_code_e;
                        String P_size_e;
                        Eng_desc = Eng_desc.Replace("<table>", "");
                        Eng_desc = Eng_desc.Replace("</table>", "");
                        Eng_desc = Eng_desc.Replace("<tr>", "");
                        Eng_desc = Eng_desc.Replace("</tr>", "");
                        Eng_desc = Eng_desc.Replace("<td>", "");
                        Eng_desc = Eng_desc.Replace("</td>", "");
                        Eng_desc = Eng_desc.Trim();
                        P_desc_e = Eng_desc.Substring(Eng_desc.IndexOf(mEngDesc)+mEngDesc.Length, Eng_desc.IndexOf(mEngCode) - Eng_desc.IndexOf(mEngDesc)-mEngDesc.Length);
                        P_code_e = Eng_desc.Substring(Eng_desc.IndexOf(mEngCode) + mEngCode.Length, Eng_desc.IndexOf(mEngSize) - Eng_desc.IndexOf(mEngCode) - mEngCode.Length);
                        P_size_e = Eng_desc.Substring(Eng_desc.IndexOf(mEngSize) + mEngSize.Length, Eng_desc.Length - Eng_desc.IndexOf(mEngSize) - mEngSize.Length);
                        
                        String P_desc_c;
                        String P_code_c;
                        String P_size_c;
                        Chi_desc = Chi_desc.Replace("<table>", "");
                        Chi_desc = Chi_desc.Replace("</table>", "");
                        Chi_desc = Chi_desc.Replace("<tr>", "");
                        Chi_desc = Chi_desc.Replace("</tr>", "");
                        Chi_desc = Chi_desc.Replace("<td>", "");
                        Chi_desc = Chi_desc.Replace("</td>", "");
                        Chi_desc = Chi_desc.Trim();
                        P_desc_c = Chi_desc.Substring(Chi_desc.IndexOf(mChiDesc) + mChiDesc.Length, Chi_desc.IndexOf(mChiCode) - Chi_desc.IndexOf(mChiDesc) - mChiDesc.Length);
                        P_code_c = Chi_desc.Substring(Chi_desc.IndexOf(mChiCode) + mChiCode.Length, Chi_desc.IndexOf(mChiSize) - Chi_desc.IndexOf(mChiCode) - mChiCode.Length);
                        P_size_c = Chi_desc.Substring(Chi_desc.IndexOf(mChiSize) + mChiSize.Length, Chi_desc.Length - Chi_desc.IndexOf(mChiSize) - mChiSize.Length);

                        dt.Rows.Add(Large, small, image_path + DDL_viewcat.SelectedValue + "/" + small, P_desc_e, P_code_e, P_size_e, P_desc_c, P_code_c, P_size_c);
                    }
                    else
                    {
                        dt.Rows.Add(Large, small, image_path + DDL_viewcat.SelectedValue + "/" + small, Eng_desc, "", "", Chi_desc, "", "");
                    }

                }

                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                GVCat.DataSource = ds;
                GVCat.DataBind();

            }

        }

#region GV_Event_handler

        protected void GVCat_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //Set the edit index.
            GVCat.EditIndex = e.NewEditIndex;
            //Bind data to the GridView control.
            binddata();
        }

        protected void GVCatRowCanceling(object sender, GridViewCancelEditEventArgs e)
        {
            GVCat.EditIndex = -1;
            //Bind data to the GridView control.
            binddata();
        }

        protected void GVCat_Rowdeleting(object sender, GridViewDeleteEventArgs e)
        {
            int item_id = e.RowIndex;
            String del_Large = ((Label)GVCat.Rows[item_id].FindControl("lbl_LargeImage")).Text;
            String del_Small = ((Label)GVCat.Rows[item_id].FindControl("lbl_ThumbnailImage")).Text;

            string filename = Server.MapPath(image_path) + DDL_viewcat.SelectedValue + "/index.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(filename);
            XmlNodeList itemsNode = doc.SelectNodes(child_node);

            string filename2 = Server.MapPath(image_path) + DDL_viewcat.SelectedValue + "/index_chi.xml";
            XmlDocument doc2 = new XmlDocument();
            doc2.Load(filename2);
            XmlNodeList itemsNode2 = doc2.SelectNodes(child_node);

            for (int i = 0; i < itemsNode.Count; i++)
            {
                XmlNode xxn = doc.SelectNodes(root_node).Item(0);
                XmlNode xn = itemsNode.Item(i);
                XmlNode xxc = doc2.SelectNodes(root_node).Item(0);
                XmlNode xc = itemsNode2.Item(i);
                String Large = xn["itemLargeImage"].InnerText;
                String small = xn["itemThumbnailImage"].InnerText;

                if ((Large == del_Large) && (small == del_Small))
                {
                    try
                    {
                        xxn.RemoveChild(xn);
                        xxc.RemoveChild(xc);
                        FileInfo largef = new FileInfo(MapPath(image_path) + "/" + DDL_viewcat.SelectedValue + "/" + del_Large);
                        if (largef.Exists)
                        {
                            File.Delete(MapPath(image_path) + "/" + DDL_viewcat.SelectedValue + "/" + del_Large);
                        }
                        FileInfo smallf = new FileInfo(MapPath(image_path) + "/" + DDL_viewcat.SelectedValue + "/" + del_Small);
                        if (smallf.Exists)
                        {
                            File.Delete(MapPath(image_path) + "/" + DDL_viewcat.SelectedValue + "/" + del_Small);
                        } 
                    }
                    catch (Exception ex)
                    {}
                }

            }
            doc.Save(filename);
            doc2.Save(filename2);
            //Bind data to the GridView control.
            binddata();
        }

        protected void GVCat_Rowbind(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex > -1)
            {
                ImageButton small_image = (ImageButton)e.Row.FindControl("img_smallImage");
                Label large_image = (Label)e.Row.FindControl("lbl_LargeImage");
                System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(image_path) + DDL_viewcat.SelectedValue + "/" + large_image.Text);
                int ActualWidth = image.Width;
                int ActualHeight = image.Height;
                small_image.Attributes.Add("onclick", "javascript:window.open('" + image_path + DDL_viewcat.SelectedValue + "/" + large_image.Text + "', 'topicsssss', 'toolbar=no, status=no, width=" + ActualWidth + ", height=" + ActualHeight + "')");
            }
        }

        protected void GVCat_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int item_id = e.RowIndex;
            String up_Large = ((Label)GVCat.Rows[item_id].FindControl("lbl_LargeImage")).Text;
            String up_Small = ((Label)GVCat.Rows[item_id].FindControl("lbl_ThumbnailImage")).Text;
            String up_Engdesc = ((TextBox)GVCat.Rows[item_id].FindControl("txt_Eng_desc")).Text;
            String up_Engcode = ((TextBox)GVCat.Rows[item_id].FindControl("txt_Eng_code")).Text;
            String up_Engsize = ((TextBox)GVCat.Rows[item_id].FindControl("txt_Eng_size")).Text;
            String up_Chidesc = ((TextBox)GVCat.Rows[item_id].FindControl("txt_Chi_desc")).Text;
            String up_Chicode = ((TextBox)GVCat.Rows[item_id].FindControl("txt_Chi_code")).Text;
            String up_Chisize = ((TextBox)GVCat.Rows[item_id].FindControl("txt_Chi_size")).Text;

            string filename = Server.MapPath(image_path) + DDL_viewcat.SelectedValue + "/index.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(filename);
            XmlNodeList itemsNode = doc.SelectNodes(child_node);

            string filename2 = Server.MapPath(image_path) + DDL_viewcat.SelectedValue + "/index_chi.xml";
            XmlDocument doc2 = new XmlDocument();
            doc2.Load(filename2);
            XmlNodeList itemsNode2 = doc2.SelectNodes(child_node);

            for (int i = 0; i < itemsNode.Count; i++)
            {
                XmlNode xn = itemsNode.Item(i);
                XmlNode xc = itemsNode2.Item(i);
                String Large = xn["itemLargeImage"].InnerText;
                String small = xn["itemThumbnailImage"].InnerText;

                if ((Large == up_Large) && (small == up_Small))
                {
                    xn["itemCaption"].InnerXml = "&lt;table&gt;&lt;tr&gt;&lt;td&gt;" + mEngDesc + "&lt;/td&gt;&lt;td&gt;" + up_Engdesc + "&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;" + mEngCode + "&lt;/td&gt;&lt;td&gt;" + up_Engcode + "&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;" + mEngSize + "&lt;/td&gt;&lt;td&gt;" + up_Engsize + "&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;";
                    xn["itemDescp"].InnerText = up_Engdesc;
                    xc["itemCaption"].InnerXml = "&lt;table&gt;&lt;tr&gt;&lt;td&gt;" + mChiDesc + "&lt;/td&gt;&lt;td&gt;" + up_Chidesc + "&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;" + mChiCode + "&lt;/td&gt;&lt;td&gt;" + up_Chicode + "&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;" + mChiSize + "&lt;/td&gt;&lt;td&gt;" + up_Chisize + "&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;";
                    xc["itemDescp"].InnerText = up_Chidesc;
                }
            }
            doc.Save(filename);
            doc2.Save(filename2);
            GVCat.EditIndex = -1;
            //Bind data to the GridView control.
            binddata();

        }

        protected void move(object sender, GridViewCommandEventArgs e)
        {
            if ((e.CommandName == "MoveUp") || (e.CommandName == "MoveDown"))
            {
                int index = Convert.ToInt32(e.CommandArgument);
                String up_Large = ((Label)GVCat.Rows[index].FindControl("lbl_LargeImage")).Text;
                String up_Small = ((Label)GVCat.Rows[index].FindControl("lbl_ThumbnailImage")).Text;
                string filename = Server.MapPath(image_path) + DDL_viewcat.SelectedValue + "/index.xml";
                XmlDocument doc = new XmlDocument();
                doc.Load(filename);
                XmlNodeList itemsNode = doc.SelectNodes(child_node);
                XmlNode eng_root = doc.SelectSingleNode(root_node);
                XmlNode current_eng_node = null;

                string filename2 = Server.MapPath(image_path) + DDL_viewcat.SelectedValue + "/index_chi.xml";
                XmlDocument doc2 = new XmlDocument();
                doc2.Load(filename2);
                XmlNodeList itemsNode2 = doc2.SelectNodes(child_node);
                XmlNode chi_root = doc2.SelectSingleNode(root_node);
                XmlNode current_chi_node = null;



                for (int i = 0; i < itemsNode.Count; i++)
                {
                    XmlNode xn = itemsNode.Item(i);
                    XmlNode xc = itemsNode2.Item(i);
                    String Large = xn["itemLargeImage"].InnerText;
                    String small = xn["itemThumbnailImage"].InnerText;

                    if ((Large == up_Large) && (small == up_Small))
                    {
                        current_eng_node = xn;
                        current_chi_node = xc;
                    }
                }

                if (e.CommandName == "MoveUp")
                { 
                    XmlNode pre_eng_node = current_eng_node.PreviousSibling;
                    XmlNode pre_chi_node = current_chi_node.PreviousSibling;

                    eng_root.InsertBefore(current_eng_node, pre_eng_node);
                    chi_root.InsertBefore(current_chi_node, pre_chi_node);
                    doc.Save(filename);
                    doc2.Save(filename2);
                    binddata();
                
                }
                else if (e.CommandName == "MoveDown")
                {
                    XmlNode next_eng_node = current_eng_node.NextSibling;
                    XmlNode next_chi_node = current_chi_node.NextSibling;

                    eng_root.InsertAfter(current_eng_node, next_eng_node);
                    chi_root.InsertAfter(current_chi_node, next_chi_node);
                    doc.Save(filename);
                    doc2.Save(filename2);
                    binddata();

                }
            }
        }

#endregion

   
}
